from ged_handler import *
# Regular Expression
import re

# This class parse a gedcom file to create an object tree
# It use the handler to parse line by line
class Parser:
    handler = None
    
    def __init__(self):
        self.handler = Handler()

    # parse a gedcom line and return a tuple
    # (<level>, <code>, <ref>, <info>)
    def parseline(self, line):
        if len(line) > 0 and line[-1] == '\n':
            line = line[:-1]
        level = int(line[0])
        # line match '<level> @<ref>@ <code> <info>'
        if re.match('[0-9]{1} @[a-zA-Z0-9]*@ [a-zA-Z0-9]+ .', line):
            subline = line[line.find('@') + 1:]
            code = subline[subline.find('@') + 2:]
            info = code[code.find(' ') + 1:]
            code = code[:code.find(' ')]
            m = re.search('@[a-zA-Z0-9]*@', line)
            ref = m.group(0)[1:-1]
        # line match '<level> @<ref>@ code'
        elif re.match('[0-9]{1} @[a-zA-Z0-9]*@ [a-zA-Z0-9]+', line):
            subline = line[line.find('@') + 1:]
            code = subline[subline.find('@') + 2:]
            m = re.search('@[a-zA-Z0-9]*@', line)
            ref = m.group(0)[1:-1]
            info = None
        # line match '<level> <code> @<ref>@'
        elif re.match('[0-9]{1} [a-zA-Z]{4} @[a-zA-Z0-9]+@', line):
            code = line[2:6]
            ref = line[8:-1]
            info = None
        # line match '<level> <code> <info>'
        elif re.match('[0-9]{1} [a-zA-Z]+ .', line):
            code = line[2:6]
            if code[3] == ' ':
                code = code[0:-1]
                info = line[6:]
            else:
                info = line[7:]
            ref = None
        # line match '<level> <code>'
        else:
            code = line[2:].strip()
            info = ref = None
        return (level, code, ref, info)
        
    def parse(self, filename):
        file = open(filename, 'r')
        lines = file.readlines()
        file.close()
        tuples = []
        for line in lines:
            tuples.append(self.parseline(line))
        #print('tuples', tuples)
        self.handler = Handler()
        for tuple in tuples:
            self.handler.handle(tuple)
        return self.handler.familyTree
